# triggertest for Sublime Text 2

import os

import sublime
import sublime_plugin

NAMEDPIPE = "triggertest.pipe" 

def trigger(root, current_file, current_line):
    try:
        fd = os.open(os.path.join(root, NAMEDPIPE), os.O_WRONLY | os.O_NONBLOCK)
        os.write(fd, "%s %s\n" % (current_file, current_line))
        os.close(fd)
    except OSError:
        pass

def walkup(name, found):
    if found:
        return name

    updir = os.path.dirname(name)
    if updir == name:
        # we are at the root
        return None

    namedpipe = os.path.join(updir, NAMEDPIPE)
    return walkup(updir, os.path.exists(namedpipe))


class TriggertestCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        row, col = self.view.rowcol(self.view.sel()[0].begin())
        row += 1
        name = self.view.file_name()
        if name:
            root = walkup(name, False)
            if root:
                trigger(root, name, row)
